/*global clearInterval: false, clearTimeout: false, document: false, event: false, frames: false, history: false, Image: false, location: false, name: false, navigator: false, Option: false, parent: false, screen: false, setInterval: false, setTimeout: false, window: false, XMLHttpRequest: false */
function updateClockElement(clockId, data, clrStyle) {
	"use strict";
	var element = document.getElementById(clockId);
	clockId.style.color = clrStyle;
	element.innerHTML = data; // show time left on element
}

// function stringTimeLeft returns formatted string in hours, minutes and secs.  
function stringTimeLeft(secondsLeft) {
	"use strict";
	var secsLeftMinusHour, hoursLeft = 0, formatTimeLeft = "";
	secsLeftMinusHour = 0; // seconds left after substraction from the hour(s).
	hoursLeft = Math.floor(secondsLeft / 3600); // calculate if more than 1
	// we got more than 1 hour
	if (hoursLeft > 0) {
		secsLeftMinusHour = secondsLeft - (hoursLeft * 3600);
	} else {
		secsLeftMinusHour = secondsLeft;
	}

	if (secsLeftMinusHour >= 60) {
		if (secsLeftMinusHour % 60 > 0) {
			if ((secondsLeft / 60) <= 5) {
				formatTimeLeft = Math.floor(secsLeftMinusHour / 60).toString()
						+ " min. " + (secsLeftMinusHour % 60).toString()
						+ " sec.";
			} 
			else { 
				formatTimeLeft = Math.round(secsLeftMinusHour / 60).toString() + " min.";
			}
		}
		else {
			if ((secsLeftMinusHour / 60) === 60) {
				formatTimeLeft = "59 min.";
		   }
		   else {
			  formatTimeLeft = (secsLeftMinusHour / 60).toString() + " min.";
		   }  
		}
	} 
	else { 
		formatTimeLeft = secsLeftMinusHour.toString() + " sec.";
	}

	if (hoursLeft > 0) {
		formatTimeLeft = hoursLeft.toString() + " hrs. " + formatTimeLeft;
	}
	
	return formatTimeLeft; // string to represent time left
}


function updateTimer(secondsLeft, clockId, submitFormId) {
	"use strict";
	// check every 3 secs how many time left.
	var timeDelta = 3, submitForm, newSecondLeft, colorStyle = "";
	submitForm = document.getElementById(submitFormId);

	newSecondLeft = secondsLeft - timeDelta;
	if (newSecondLeft >= 0) {
		if (newSecondLeft <= 120) {
			// make element content red last 2 minutes
			colorStyle = "red";
		} 
		else {
			colorStyle = "green";
		}
  
		// Write TimeLeft on element clockId with a formatted string
		updateClockElement(clockId, stringTimeLeft(secondsLeft), colorStyle);

		// call the function again
		setTimeout(function () {
			updateTimer(newSecondLeft, clockId, submitFormId);
		}, 1000 * timeDelta);
	} else { // Time is up
		submitForm.submit();
	}
}
